package cn.appsys.controller.dev;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;

import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.pojo.DevUser;
import cn.appsys.service.data.DataDictionaryService;
import cn.appsys.service.dev.appinfo.AppInfoService;
import cn.appsys.service.dev.category.AppCategoryService;
import cn.appsys.service.dev.version.AppVersionService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.PageSupport;

@Controller
@RequestMapping("/dev/flatform/app")
public class DevAppController {
	
	private Logger log = Logger.getLogger(DevAppController.class);
	
	@Resource
	private DataDictionaryService dataDicService;
	
	@Resource
	private AppCategoryService appCategoryService;

	@Resource
	private AppInfoService appInfoService;
	
	@Resource
	private AppVersionService appversionService;
	
	/**
	 * 异步获取三级分类
	 * @return
	 */
	@RequestMapping(value="/queryCategorylist",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public String queryCategorylist(@RequestParam(value="pid",required = false)Integer parentId) {
		log.debug("parentId ====> "+parentId);
		return JSONArray.toJSONString(appCategoryService.queryCategoryLevel2(parentId));
	}
	
	/**
	 * 异步获取所属平台
	 * @return
	 */
	@RequestMapping(value="/datadictionarylist.json",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public String datadictionarylist(@RequestParam(value="tcode",required = false)String typeCode) {
		return JSONArray.toJSONString(dataDicService.getStatusList(typeCode));
	}
	
	/**
	 * 异步验证APK名称是否存在
	 * @return
	 */
	@RequestMapping(value="/apkexist",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public String apkexist(AppInfo appinfo,@RequestParam(value="APKName",required = false)String APKName) {
		HashMap<String,String> resultMap = new HashMap<String,String>();
		appinfo.setAPKName(APKName);
		AppInfo appList = appInfoService.getAppInfo(appinfo);
		if (APKName == null || APKName == "") {
			resultMap.put("APKName", "empty");
		}else {
			if (appList != null) {
				resultMap.put("APKName", "exist");
			}else {
				resultMap.put("APKName", "noexist");
			}
		}
		return JSONArray.toJSONString(resultMap);
	}
	
	/**
	 * 异步删除LOGO图片
	 * @return
	 */
	@RequestMapping(value="/delfile",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public String delfile(AppInfo appinfo,HttpServletRequest request,HttpSession session,
			@RequestParam(value="id",required = false)Integer id) {
		HashMap<String,String> resultMap = new HashMap<String,String>();
		appinfo.setId(id);
		appinfo.setCreatedBy(((DevUser)session.getAttribute(Constants.DEV_USER)).getId());
		appinfo.setCreationDate(new Date());
		AppInfo appList = appInfoService.getAppInfo(appinfo);
		if (appList == null) {
			resultMap.put("result", "empty");
		}else {
			//删除保存的图片
			if (appList.getLogoLocPath() != null) {
				File file = new File(appList.getLogoLocPath());
				file.delete();
				//修改图片路径为空
				if(appInfoService.delfile(appinfo) > 0) {
					resultMap.put("result", "success");
				}else {
					resultMap.put("result", "failed");
				}
			}
		}
		return JSONArray.toJSONString(resultMap);
	}
	
	/**
	 * 异步删除apk文件
	 * @return
	 */
	@RequestMapping(value="/delAPKFile",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public String delAPKFile(@RequestParam(value="id",required = false)Integer id) {
		HashMap<String,String> resultMap = new HashMap<String,String>();
		System.out.println("delAPKFile id："+id);
		AppVersion appList = appversionService.getAppVersion(id);
		if (appList == null) {
			resultMap.put("result", "failed");
		}else {
			//删除保存的apk
			if (appList.getApkLocPath() != null) {
				File file = new File(appList.getApkLocPath());
				file.delete();
				//修改apk路径为空
				if(appversionService.updateAppVersionapkfile(id) > 0) {
					resultMap.put("result", "success");
				}else {
					resultMap.put("result", "failed");
				}
			}
		}
		return JSONArray.toJSONString(resultMap);
	}
	
	/**
	 * 上架操作
	 * @return
	 */
	@RequestMapping(value="{id}/{saleSwitch}/sale",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public String saleSwitchAjax(@PathVariable Integer id,@PathVariable(value="saleSwitch",required = false)String saleSwitch) {
		HashMap<String,String> resultMap = new HashMap<String,String>();
		System.out.println("id："+id);
		System.out.println(saleSwitch);
		AppInfo appinfo = new AppInfo();
		appinfo.setId(id);
		if (appInfoService.getAppInfo(appinfo) == null) {
			resultMap.put("errorCode", "exception000001");
		}else {
			resultMap.put("errorCode", "0");
			if (saleSwitch.equals("open")) {
				if (appInfoService.saleSwitchPgUp(id) > 0) {
					resultMap.put("resultMsg", "success");
				}else {
					resultMap.put("resultMsg", "failed");
				}
			}else if(saleSwitch.equals("close")){
				if (appInfoService.saleSwitchPgDn(id) > 0) {
					resultMap.put("resultMsg", "success");
				}else {
					resultMap.put("resultMsg", "failed");
				}
			}
		}
		return JSONArray.toJSONString(resultMap);
	}
	
	
	
	
	/**
	 * 删除APP信息
	 * @return
	 */
	@RequestMapping(value="/delapp",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public String delapp(@RequestParam(value="id",required = false)Integer id) {
		HashMap<String,String> resultMap = new HashMap<String,String>();
		System.out.println("id："+id);
		AppInfo appinfo = appInfoService.queryappinfoview(id);
		if (appinfo == null) {
			resultMap.put("delResult", "notexist");
		}else {
			//删除版本信息
			if (appInfoService.delappversion(id) > 0) {
				//删除app信息
				appInfoService.delapp(id);
				resultMap.put("delResult", "true");
			}else {
				resultMap.put("delResult", "false");
			}
		}
		return JSONArray.toJSONString(resultMap);
	}

	
	
	/**
	 * 查看APP信息
	 * @return
	 */
	@RequestMapping(value="/appview/{id}",method = RequestMethod.GET)
	public String appview(@PathVariable Integer id,Model model) {
		model.addAttribute("appInfo",appInfoService.queryappinfoview(id));
		model.addAttribute("appVersionList",appversionService.getAppVersionList(id));
		return "developer/appinfoview";
	}
	
	
	/**
	 * 进入修改App最新版本信息页面
	 * @return
	 */
	@RequestMapping(value="/appversionmodify",method = RequestMethod.GET)
	public String appversionmodify(Model model,AppVersion appVersion,
				@RequestParam(value="aid",required = false)Integer appinfoid,
				@RequestParam(value="vid",required = false)Integer versionid) {
		
		log.debug("aid===>"+appinfoid);
		log.debug("vid===>"+versionid);
				
		model.addAttribute("appVersion",appversionService.getAppVersion(versionid));
		model.addAttribute("appVersionList",appversionService.getAppVersionList(appinfoid));
		return "developer/appversionmodify";
	}
	
	/**
	 * 保存修改的最新版本信息
	 * @return
	 */
	@RequestMapping(value="/appversionmodifysave",method=RequestMethod.POST)
	public String appversionmodifysave(AppVersion appVersion,Model model,HttpSession session,HttpServletRequest request,
				@RequestParam(value="attach",required = false)MultipartFile attach) {
		
		String downloadLink =  null;
		String apkLocPath = null;
		String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
		log.info("uploadFile path ==================>"+path);
		//判断文件是否为空
		if (!attach.isEmpty()) {
			String oldFileName = attach.getOriginalFilename();	//原文件名
			log.info("uploadFile oldFileName ==================>"+oldFileName);
			String suffix = FilenameUtils.getExtension(oldFileName);//原文件后缀
			log.debug("uploadFile suffix ==================>"+suffix);
			int filesize = 50000000;
			log.debug("uploadFile size ==================>"+attach.getSize());
			if (attach.getSize() > filesize) {//上传大小不得超过500MB
				model.addAttribute("fileUploadError", "* 上传文件大小不得超过50KB");
			}else if (suffix.equalsIgnoreCase("apk")) {//判断上传图片格式是否正确
				//APK名称
				AppInfo app = new AppInfo();
				app.setId(appVersion.getAppId());
				AppInfo appInfo = appInfoService.getAppInfo(app);
				String apkFileName = appInfo.getAPKName()+"-"+appVersion.getVersionNo()+".apk";
				log.debug("new fileName======="+attach.getName());
				File targetFile = new File(path,apkFileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				//保存
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					model.addAttribute("fileUploadError,", "* 上传失败!");
				}
				apkLocPath = path + File.separator + apkFileName;								//绝对路径
				downloadLink = request.getContextPath()+"/statics/uploadfiles/"+apkFileName;	//相对路径
				
			}else {
				model.addAttribute("fileUploadError,", "* 上传图片格式不正确");
			}
		}
		System.out.println(appVersion.getVersionNo());
		System.out.println(appVersion.getVersionSize());
		System.out.println(appVersion.getPublishStatus());
		System.out.println(apkLocPath);
		System.out.println(downloadLink);
		
		appVersion.setModifyBy(((DevUser)session.getAttribute(Constants.DEV_USER)).getId());
		appVersion.setModifyDate(new Date());
		appVersion.setApkLocPath(apkLocPath);
		appVersion.setDownloadLink(downloadLink);
		if (appversionService.updateAppVersion(appVersion) > 0) {
			System.out.println("ok");
			return "redirect:/dev/flatform/app/list";
		}
		
		return "developer/appversionmodify";
	}
	
	
	/**
	 * 进入新增APP版本信息页面
	 * @return
	 */
	@RequestMapping(value="/appversionadd",method = RequestMethod.GET)
	public String appversionadd(Model model,AppVersion appVersion,@RequestParam(value="id",required = false)Integer appId) {
		appVersion.setAppId(appId);	//保存选择好要新增版本信息的对象id
		model.addAttribute("appVersion",appVersion);
		model.addAttribute("appVersionList",appversionService.getAppVersionList(appId));
		return "developer/appversionadd";
	}
	
	/**
	 * 保存APP版本信息
	 * @return
	 */
	@RequestMapping(value="/addversionsave",method = RequestMethod.POST)
	public String addversionsave(AppVersion appVersion,Model model,
					HttpSession session,HttpServletRequest request,
					@RequestParam(value="a_downloadLink",required = false)MultipartFile attach) {
		
		String downloadLink =  null;
		String apkLocPath = null;
		boolean flag = true;
		String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
		log.info("uploadFile path ==================>"+path);
		//判断文件是否为空
		if (!attach.isEmpty()) {
			String oldFileName = attach.getOriginalFilename();	//原文件名
			log.info("uploadFile oldFileName ==================>"+oldFileName);
			String suffix = FilenameUtils.getExtension(oldFileName);//原文件后缀
			log.debug("uploadFile suffix ==================>"+suffix);
			int filesize = 50000000;
			log.debug("uploadFile size ==================>"+attach.getSize());
			if (attach.getSize() > filesize) {//上传大小不得超过500MB
				model.addAttribute("fileUploadError", "* 上传文件大小不得超过50KB");
				flag = false;
			}else if (suffix.equalsIgnoreCase("apk")) {//判断上传图片格式是否正确
				//APK名称
				AppInfo app = new AppInfo();
				app.setId(appVersion.getAppId());
				AppInfo appInfo = appInfoService.getAppInfo(app);
				String apkFileName = appInfo.getAPKName()+"-"+appVersion.getVersionNo()+".apk";
				log.debug("new fileName======="+attach.getName());
				File targetFile = new File(path,apkFileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				//保存
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					model.addAttribute("fileUploadError,", "* 上传失败!");
					flag = false;
				}
				apkLocPath = path + File.separator + apkFileName;								//绝对路径
				downloadLink = request.getContextPath()+"/statics/uploadfiles/"+apkFileName;	//相对路径
				
				
				appVersion.setApkFileName(apkFileName);
				appVersion.setCreatedBy(((DevUser)session.getAttribute(Constants.DEV_USER)).getId());
				appVersion.setCreationDate(new Date());
				appVersion.setApkLocPath(apkLocPath);
				appVersion.setDownloadLink(downloadLink);
			}else {
				model.addAttribute("fileUploadError,", "* 上传图片格式不正确");
				flag = false;
			}
		}
		
		if (flag) {
			if (appversionService.addversion(appVersion) > 0) {
				//新增成功之后修改App_info表中versionId字段
				AppInfo appinfo = new AppInfo();
				appinfo.setId(appVersion.getAppId());
				System.out.println(appVersion.getId());
				appinfo.setVersionId(appVersion.getId());
				int result = appInfoService.appinfoModify(appinfo);
				if (result > 0) {
					return "redirect:/dev/flatform/app/list";					
				}else {
					return "developer/appversionadd";
				}
			}
		}
		
		return "developer/appversionadd";
	}
	
	
	/**
	 * 按条件查询信息,app维护页面(appinfolist.jsp)
	 * @return
	 */
	@RequestMapping(value="/list")
	public String appinfo(Model model,
				@RequestParam(value="querySoftwareName",required = false)String querySoftwareName,
				@RequestParam(value="queryStatus",required = false)Integer queryStatus,
				@RequestParam(value="queryFlatformId",required = false)Integer queryFlatformId,
				@RequestParam(value="queryCategoryLevel1",required = false)Integer queryCategoryLevel1,
				@RequestParam(value="queryCategoryLevel2",required = false)Integer queryCategoryLevel2,
				@RequestParam(value="queryCategoryLevel3",required = false)Integer queryCategoryLevel3,
				@RequestParam(value="pageIndex",required = false)Integer pageIndex) {
		
		log.debug("querySoftwareName ====> "+querySoftwareName);
		log.debug("queryStatus ====> "+queryStatus);
		log.debug("queryFlatformId ====> "+queryFlatformId);
		log.debug("queryCategoryLevel1 ====> "+queryCategoryLevel1);
		log.debug("queryCategoryLevel2 ====> "+queryCategoryLevel2);
		log.debug("queryCategoryLevel3 ====> "+queryCategoryLevel3);
		
		
		//获取APP状态
		List<DataDictionary> statusList = dataDicService.getStatusList("APP_STATUS");
		
		//获取所属平台
		List<DataDictionary> flatFormList = dataDicService.getStatusList("APP_FLATFORM");
		
		//一级分类下拉框
		List<AppCategory> categoryLevel1List = appCategoryService.queryCategoryLevel2(0);
		
		//设置页码容量
		int pageSize = Constants.pageSize;
		
		//当前页
		int currentPageNo = 1;
		
		if (pageIndex != null) {
			try {
				currentPageNo = Integer.valueOf(pageIndex);
			} catch (NumberFormatException e) {
				return "redirect:/403";
			}
		}
		
		//按条件获取总记录数
		Integer totalCount = appInfoService.getAppInfoCount(querySoftwareName, queryStatus,
				queryFlatformId, queryCategoryLevel1, queryCategoryLevel2, queryCategoryLevel3);
		System.out.println(totalCount);
		
		//分页计算类
		PageSupport pages = new PageSupport(totalCount,currentPageNo,pageSize);
		int totalPageCount = pages.getTotalPage();
		
		//控制首页和尾页
		if (currentPageNo < 1) {
			currentPageNo = 1;
		}else if(currentPageNo > totalPageCount) {
			currentPageNo = totalPageCount;
		}
		
		//分页获取数据
		List<AppInfo> appInfoList = appInfoService.getAppInfoList(querySoftwareName, queryStatus,
				queryFlatformId, queryCategoryLevel1, queryCategoryLevel2, queryCategoryLevel3,(currentPageNo-1)*pageSize,pageSize);
		
		model.addAttribute("pages",pages);
		model.addAttribute("appInfoList",appInfoList);
		model.addAttribute("categoryLevel1List",categoryLevel1List);
		model.addAttribute("statusList",statusList);
		model.addAttribute("flatFormList",flatFormList);
		// 将查询条件也保存到模型中
		model.addAttribute("querySoftwareName", querySoftwareName);
		model.addAttribute("queryStatus", queryStatus);
		model.addAttribute("queryflatformId", queryFlatformId);
		model.addAttribute("queryCategoryLevel1", queryCategoryLevel1);
		model.addAttribute("queryCategoryLevel2", queryCategoryLevel2);
		model.addAttribute("queryCategoryLevel3", queryCategoryLevel3);
		return "developer/appinfolist";
	}

	/**
	 * 进入新增app信息页面
	 * @return
	 */
	@RequestMapping(value="/appinfoadd",method=RequestMethod.GET)
	public String addAppInfo() {
		return "developer/appinfoadd";
	}
	
	
	/**
	 * 保存appinfo新增信息
	 * @return
	 */
	@RequestMapping(value="/appinfoaddsave",method=RequestMethod.POST)
	public String appinfoaddSave(Model model,HttpSession session,AppInfo appinfo,HttpServletRequest request,
					@RequestParam(value="a_logoPicPath",required = false) MultipartFile attach) {
		
		
		String logoPicPath = null;
		String logoLocPath = null;
		boolean flag = true;
		String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
		log.info("uploadFile path ==================>"+path);
		//判断文件是否为空
		if (!attach.isEmpty()) {
			String oldFileName = attach.getOriginalFilename();	//原文件名
			log.info("uploadFile oldFileName ==================>"+oldFileName);
			String suffix = FilenameUtils.getExtension(oldFileName);//原文件后缀
			log.debug("uploadFile suffix ==================>"+suffix);
			int filesize = 50000;
			log.debug("uploadFile size ==================>"+attach.getSize());
			if (attach.getSize() > filesize) {//上传大小不得超过50KB
				model.addAttribute("fileUploadError", "* 上传文件大小不得超过50KB");
				flag = false;
			}else if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png") 
					|| suffix.equalsIgnoreCase("jpeg") || suffix.equalsIgnoreCase("pneg")) {//判断上传图片格式是否正确
				//APK名称
				String fileName = appinfo.getAPKName()+".jpg";
				log.debug("new fileName======="+attach.getName());
				File targetFile = new File(path,fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				//保存
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					model.addAttribute("fileUploadError,", "* 上传失败!");
					flag = false;
				}
				logoPicPath = request.getContextPath() + "/static" + "/uploadfiles/" + fileName;	//相对路径
				logoLocPath = path + File.separator + fileName;								//绝对路径
				
				System.out.println(appinfo.getSoftwareName());
				System.out.println(fileName);
				System.out.println(appinfo.getSupportROM());
				System.out.println("logoPicPath:"+logoPicPath);
				System.out.println("logoLocPath："+logoLocPath);
				
				appinfo.setLogoPicPath(logoPicPath);
				appinfo.setLogoLocPath(logoLocPath);
				appinfo.setDevId(((DevUser)session.getAttribute(Constants.DEV_USER)).getId());
				appinfo.setCreatedBy(((DevUser)session.getAttribute(Constants.DEV_USER)).getId());
				appinfo.setCreationDate(new Date());
			}else {
				model.addAttribute("fileUploadError,", "* 上传图片格式不正确");
				flag = false;
			}
		}
		
		if (flag) {
			if(appInfoService.addAppInfo(appinfo) > 0) {
				return "redirect:/dev/flatform/app/list"; //新增成功跳转到app列表信息页面
			}else {
				return "developer/appinfoadd"; //新增失败又跳转回新增页面
			}
		}
		
		
		return "developer/appinfoadd";
	}
	
	
	/**
	 * 进入修改appinfo基本信息
	 * @return
	 */
	@RequestMapping(value="/appinfomodify",method=RequestMethod.GET)
	public String modifyAppinfo(Model model,AppInfo appinfo,@RequestParam(value="id",required = false)Integer appinfoid) {
		appinfo.setId(appinfoid);
		model.addAttribute("appInfo",appInfoService.getAppInfo(appinfo));
		return "developer/appinfomodify";
	}

	
	
	/**
	 * 保存修改appinfo基本信息
	 * @return
	 */
	@RequestMapping(value="/appinfomodifysave",method=RequestMethod.POST)
	public String appinfomodifySave(AppInfo appinfo,HttpSession session,Model model,HttpServletRequest request,
			@RequestParam(value="attach",required = false)MultipartFile attach) {
		
		String logoPicPath = null;
		String logoLocPath = null;
		boolean flag = true;
		String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
		log.info("uploadFile path ==================>"+path);
		//判断文件是否为空
		if (!attach.isEmpty()) {
			String oldFileName = attach.getOriginalFilename();	//原文件名
			log.info("uploadFile oldFileName ==================>"+oldFileName);
			String suffix = FilenameUtils.getExtension(oldFileName);//原文件后缀
			log.debug("uploadFile suffix ==================>"+suffix);
			int filesize = 50000;
			log.debug("uploadFile size ==================>"+attach.getSize());
			if (attach.getSize() > filesize) {//上传大小不得超过50KB
				model.addAttribute("fileUploadError", "* 上传文件大小不得超过50KB");
				flag = false;
			}else if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png") 
					|| suffix.equalsIgnoreCase("jpeg") || suffix.equalsIgnoreCase("pneg")) {//判断上传图片格式是否正确
				//APK名称
				String fileName = appinfo.getAPKName()+".jpg";
				log.debug("new fileName======="+attach.getName());
				File targetFile = new File(path,fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				//保存
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					model.addAttribute("fileUploadError,", "* 上传失败!");
					flag = false;
				}
				logoPicPath = request.getContextPath() + "/static" + "/uploadfiles/" + fileName;	//相对路径
				logoLocPath = path + File.separator + fileName;								//绝对路径
				
				appinfo.setLogoPicPath(logoPicPath);
				appinfo.setLogoLocPath(logoLocPath);
				appinfo.setDevId(((DevUser)session.getAttribute(Constants.DEV_USER)).getId());
				appinfo.setModifyBy(((DevUser)session.getAttribute(Constants.DEV_USER)).getId());
				appinfo.setModifyDate(new Date());
			}
		}
		
		if (flag) {
			if(appInfoService.appinfoModify(appinfo) > 0) {
				return "redirect:/dev/flatform/app/list"; //修改成功跳转到app列表信息页面
			}else {
				return "developer/appinfomodify"; //修改失败又跳转回修改页面
			}
		}
		return "developer/appinfomodify"; //修改失败又跳转回修改页面
	}
	
}
